"use client";
import CharPinyinMarker from "@ccpt/CharPinYinMarker";
import {
  CharCategory,
  CharPinyinInfo,
  PinYinStatus,
} from "@ccpt/CharPinYinMarker/meta";
import { useMemoizedFn, useSafeState } from "ahooks";
import * as styles from "./styles";
import { Button, Input } from "antd";
import { getOrDie } from "@/utils";

export default function ArticlePinYinMarker() {
  const [content, setContent] = useSafeState("");
  const [data, setData] = useSafeState<CharPinyinInfo[]>([]);
  const [loading, setLoading] = useSafeState(false);

  const onGenerateClick = useMemoizedFn(async () => {
    setLoading(true);
    const res = await fetch("/api/pinyin/generate", {
      method: "POST",
      body: JSON.stringify({
        content,
      }),
    });
    const { words } = (await res.json()) as {
      words: Array<{ word: string; pinyin?: string[] }>;
    };

    const ans: CharPinyinInfo[] = [];
    for (const { word, pinyin } of words) {
      if (!pinyin) {
        ans.push({ char: word, category: CharCategory.Other });
      } else {
        if (word.length === 1) {
          ans.push({
            char: word,
            category: CharCategory.Character,
            pinyin: {
              options: pinyin,
              status: PinYinStatus.Auto,
            },
          });
        } else {
          const chars = word.split("");
          const pinyins = pinyin[0].split(" ");
          for (let i = 0; i < chars.length; ++i) {
            ans.push({
              char: chars[i],
              category: CharCategory.Character,
              pinyin: {
                options: [],
                status: PinYinStatus.Auto,
                recommend: pinyins[i],
              },
            });
          }
        }
      }
    }

    setLoading(false);
    setData(ans);
  });

  return (
    <styles.Wrapper>
      <h1>汉语拼音标注</h1>

      <Input.TextArea
        onChange={(e) => setContent(e.target.value)}
        placeholder={"需要标注的内容"}
      />

      <Button type={"primary"} onClick={onGenerateClick}>
        生成拼音
      </Button>

      {loading ? (
        <div className={"center-box"}>加载中</div>
      ) : data.length ? (
        <CharPinyinMarker
          data={data}
          onChange={(pinyin, idx) => {
            const info = getOrDie(data[idx].pinyin);
            info.value = pinyin;
            info.status = PinYinStatus.Confirmed;
            setData([...data]);
          }}
          onConfirm={(idx) => {
            const info = getOrDie(data[idx].pinyin);
            info.value = info.options[0];
            info.status = PinYinStatus.Confirmed;
            setData([...data]);
          }}
        />
      ) : (
        <div className={"center-box"}>无数据</div>
      )}
    </styles.Wrapper>
  );
}
